package mail

import (
	"fmt"
	"net/smtp"
	"strings"
)

type loginAuth struct {
	identity string
	host     string
	username string
	password string
}

func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
	// if server.Name != a.host {
	// 	return "", nil, errors.New("wrong host name")
	// }
	resp := []byte(a.username)
	return "LOGIN", resp, nil
}

func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
	msg := string(fromServer)
	if !more {
		return nil, nil
	}
	if msg != `Password:` {
		return nil, fmt.Errorf("Auth Next: server response [%s]", msg)
	}
	return []byte(a.password), nil
}

// SendMail 发送给指定的邮箱列表
func SendMail(host, from, username, passwd, nick string, to []string, subject, body string) error {
	// auth := &loginAuth{
	// 	identity: "",
	// 	host:     host,
	// 	username: username,
	// 	password: passwd,
	// }
	vec := strings.Split(host, `:`)
	auth := smtp.PlainAuth(``, username, passwd, vec[0])
	contenttype := "Content-Type: text/html; charset=UTF-8"
	msg := "To: " + strings.Join(to, ",") + "\r\n" +
		"From: " + nick + "<" + from + ">\r\n" +
		"Subject: " + subject + "\r\n" +
		contenttype + "\r\n\r\n" + body
	err := smtp.SendMail(host, auth, from, to, []byte(msg))
	if err != nil {
		return fmt.Errorf("mail.SendMail failed: %v", err)
	}
	return nil
}
